import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wan_android/api/user.dart';
import 'package:wan_android/model/user/user_info_type.dart';
import 'package:wan_android/model/user/user_type.dart';

class UserPageModel extends ChangeNotifier {
  UserType? _user;
  UserInfoType? _userInfo;

  UserType? get user => _user;
  UserInfoType? get userInfo => _userInfo;

  Future getStorageInfo() async {
    final prefs = await SharedPreferences.getInstance();
    String? userInfo = prefs.getString('userInfo');
    if (userInfo != null) {
      Map<String, dynamic> temp = jsonDecode(userInfo);
      _userInfo = UserInfoType.fromJson(temp);
    }
    notifyListeners();
  }

  Future getInfo() async {
    Map<String, dynamic> response = await getUserInfo();
    UserInfoRes userInfoData = UserInfoRes.fromJson(response);
    if (userInfoData.data != null) {
      _userInfo = userInfoData.data;
    }
    notifyListeners();
  }

  Future onRegister(data) async {
    Map<String, dynamic> response = await register(data);
    if (response['errorCode'] == 0) {
      return true;
    }
    return false;
  }
  
  // 登录
  Future onLogin(data) async {
    Map<String, dynamic> response = await login(data);
    UserInfoRes userInfoData = UserInfoRes.fromJson(response);
    if (userInfoData.data != null) {
      _userInfo = userInfoData.data;
      final prefs = await SharedPreferences.getInstance();
      prefs.setString('userInfo', jsonEncode(_userInfo));
    }
    notifyListeners();
  }

  Future onLogout() async {
    final prefs = await SharedPreferences.getInstance();
    Map<String, dynamic> response = await logout();
    // 退出成功
    if (response['errorCode']) {
      await prefs.clear();
    }
    print('退出======');
    print(response);
    notifyListeners();
  }

  // 添加收藏
  addFav(int articleId) async {
    final prefs = await SharedPreferences.getInstance();
    _userInfo!.collectIds.add(articleId);
    prefs.setString('userInfo', jsonEncode(_userInfo));
    notifyListeners();
  }

  // 删除收藏
  removeFav(int articleId) async {
    final prefs = await SharedPreferences.getInstance();
    _userInfo!.collectIds.remove(articleId);
    prefs.setString('userInfo', jsonEncode(_userInfo));
    notifyListeners();
  }

  // 清空收藏
  clearFav() async {
    final prefs = await SharedPreferences.getInstance();
    _userInfo!.collectIds = [];
    prefs.setString('userInfo', jsonEncode(_userInfo));
    notifyListeners();
  }
}